<?php
/**
 * Created by PhpStorm.
 * User: 84071
 * Date: 2017-09-07
 * Time: 11:47
 */
namespace app\common\model;
use think\Db;
use think\db\Query;
use think\Model;

class Order extends Model{

    // 启用状态
    protected function getplaystatuszhAttr($value,$data){
        $playstatus = [ 0 => '<a class="button button-S bg-yellow">未付款</a>',1 => '<a class="button button-S bg-blue">已付款</a>',2 => '<a class="button button-S bg-green">已发货</a>',3 => '<a class="button button-S bg-red">已退款</a>',4 => '<a class="button button-S bg-red">付款中</a>',5 => '<a class="button button-S bg-red">已收货</a>',6 => '<a class="button button-S bg-red">申请退款</a>'];
        return $playstatus[$data['playstatus']];
    }
    // 关联订单附加资料表
    public function orderdb(){
        return $this->hasOne('OrderCont','oid','oid');
    }

    /**
     * @param $data
     * 必须参数  aid 商品id   uid 用户id    authstock 是否自动减库存   code 商品筛选条件 authstatus 是否自动支付
     * 自动支付仅支持  0 余额支付  1 积分支付  2  虚拟币支付
     * @return mixed
     */
    public function add_order($data){
        //  查询产品信息
        $shop = $data['shop'];
        $resorder['code'] = '0';

        //  获取用户信息
        $user = empty($data['user']) ? null : $data['user'];
        if(empty($data['user'])){
            $userdata = \model('UserData')->where('uid',$data['uid'])->find()->toArray();
            $user['uname'] = $userdata['uname'];
            $user['uphone'] = $userdata['uphone'];
            $user['uaddress'] = $userdata['uaddress'];
        }
        //  定义初始价格
        $oid = 'CXR'.date("Ymd").$this->addoid();
        $allmoney = $newmoney = $pricemoney = $newpimoney = '0';
        $artmodel = new ArtModel();
        foreach ($shop as $k => $v){
            $arr = \model('Article')->where('aid',$v['aid'])->find();
            $arr = \model('Article')->get_onedata($arr);
            // 检测产品库存
            if(!empty($data['authstock']) && $data['authstock'] == '1'){
                $map = null;
                foreach ($data['cont'] as $k1 => $v1){
                    foreach ($v1 as $k2 => $v2){
                        $map[$k2] = $v2;
                    }
                }
                if(!empty($map)){
                    $num = \model('OrderCont')->where('aid',$arr['aid'])->where($map)->sum('num');
                }else{
                    $num = \model('OrderCont')->where('aid',$arr['aid'])->sum('num');
                }
                if(!empty($arr['stock'])){
                    $arr['stock'] = $arr['stock'] - $num;
                }
            }
            if(!empty($arr['stock'])){
                if($arr['stock'] < $v['num']){
                    $resorder['msg'] = '产品库存不足，请重新选择！';
                    return $resorder;
                }
            }
            //  产品数据验证
            if(isset($data['code'])){
                foreach ($data['code'] as $v1){
                    switch ($v1['class']){
                        case 'time':
                            $dtime = strtotime($arr[$v1['name']]);
                            if(empty($v1['value'])){
                                $v1['value'] = time();
                            }
                            if($v1['value'].$v1['where'].$dtime == false){
                                $resorder['msg'] = '产品选择错误！';
                                return $resorder;
                            }
                            break;
                    }
                }
            }

            //  获取所有模型字段
            $files = $artmodel->editfile($arr['mid']);
            $shopsales = $shopmoney = $shopfile = null;
            foreach ($files as $k1 => $v1){
                if($v1['formtype'] == 'shopsales'){
                    $shopsales = $k1;
                    continue;
                }
                if($v1['formtype'] == 'shopmoney'){
                    $shopmoney = $k1;
                    continue;
                }
                if($v1['formtype'] == 'shopfile'){
                    $shopfile = $k1;
                    continue;
                }
            }
            //  检测价格
            $v['money']['money'] = $arr['money'];
            if(!empty($shopmoney) && $arr[$shopmoney]){
                foreach ($arr[$shopmoney] as $k1 => $v1){
                    if($v1['title'] == $v['money']['value']){
                        $v['money']['money'] = $v1['value'];
                    }
                }
            }
            //  检测是否存在促销字段
            if(!empty($shopsales) && $arr[$shopsales]){
                foreach ($arr[$shopsales] as $k2 => $v2){
                    $volume[$k2]  = $v2['title'];
                    $edition[$k2] = $v2['value'];
                }
                $ret = arraySort($arr[$shopsales], 'title');
                $arr['shopsales'] = array_values($ret);
                $dnum = '0';
                foreach ($arr['shopsales'] as $k2 => $v2){
                    if($v['num'] > $dnum && $v['num'] <= $v2['title']){
                        $v['money']['newmoney'] = $v['money']['money'] * $v2['value'] / 10;
                        break;
                    }
                }
            }
            if(!empty($v['money']['newmoney'])){
                $pimoney = $v['money']['money'];
                $newpimoney = bcmul($pimoney,100);
                $newpimoney = bcmul($newpimoney,$v['num']);
                $v['money'] = $v['money']['newmoney'];
                $newmoney = bcmul($v['money'],100);
                $newmoney = bcmul($newmoney,$v['num']);
                $allmoney = $allmoney + $newpimoney;
                $pricemoney = $pricemoney + $newmoney;
            }else{
                $v['money'] = $v['money']['money'];
                $newmoney = bcmul($v['money'],100);
                $newmoney = bcmul($newmoney,$v['num']);
                $allmoney = $allmoney + $newmoney;
                $pricemoney = $pricemoney + $newmoney;
            }
            $v['oid'] = $oid;
            $v['uid'] = $data['uid'];
            $v['title'] = $arr['title'];
            $v['picurl'] = $arr['picurl'];
            $aids[] = $v['aid'];
            $newshop[] = $v;
        }
        //  处理支付状态 如果不是人民币订单，则检测积分或虚拟币是否足够
        if($data['class'] != '0') {
            $moneymodel = new UserMoney();
            $getmoney = array(
                'uid' => $data['uid'],
                'money_class' => $data['class'],
            );
            $usermoney = $moneymodel->get_money($getmoney);
            if ($usermoney == false) {
                $resorder['msg'] = '余额不足！';
                return $resorder;
            }

            if($usermoney['user_money'] < ($allmoney / 100)){
                $resorder['msg'] = '余额不足！';
                return $resorder;
            }
        }
        $aids = arrayFlip($aids);
        $aids = implode(',',$aids);
        //  打包conf数据
        $conf['user'] = $user;
        $conf['shop'] = $newshop;
        $conf = serialize($conf);
        //  创建订单数组
        $order = array(
            'oid' => $oid,
            'uid' => $data['uid'],
            'aid' => $aids,
            'mid' => $data['mid'],
            'title' => "购物订单".$oid,
            'uphone' => $user['uphone'],
            'allmoney' => $allmoney,
            'pricemoney' => $pricemoney,
            'playstatus' => '0',
            'addtime' => time(),
            'conf' => $conf,
            'class' => $data['class'],
            'playtime' => '',
        );
        //  处理订单
        if($this->allowField(true)->save($order)){
            foreach ($newshop as $v){
                \model('OrderCont')->setAttr('id',null)->allowField(true)->isUpdate(false)->save($v);
            }
            //  如果需要自动支付，则传入此参数，值为1
            if(!empty($data['authstatus']) && $data['authstatus'] == '1'){
                $order['money_class'] = $data['class'];
                if($moneymodel->add_pay($order,$allmoney / 100)){
                    $this->where('oid',$order['oid'])->update(['playstatus'=>'1','playtime'=>time()]);
                    $resorder['code'] = '1';
                    $resorder['msg'] = '订单支付成功！';
                    return $resorder;
                }
            }
            $resorder['code'] = '2';
            $resorder['oid'] = $order['oid'];
            $resorder['msg'] = '下单成功！';
            return $resorder;
        }else{
            $resorder['msg'] = '下单失败，请重新下单！';
            return $resorder;
        }
    }
    // 充值与特约费订单添加
    public function add_chong($data){
        if($this->save($data)){
            return true;
        }else{
            return false;
        }
    }
    // 生成订单编号
    protected function addoid(){
        $numbers = range (1,50);
        shuffle ($numbers);
        $num=8;
        $result = array_slice($numbers,0,$num);
        $result = implode('',$result);
        $newname = '';
        for ( $i = 0; $i < 8; $i++ ) {
            $newname .= substr($result, mt_rand(0, strlen($result) - 1), 1);
        }
        return $newname;
    }
    // 查询
    public function get_list($data){
        //  初始化查询条件
        $aid = empty($data['aid'])?null:$data['aid'];
        $oid = empty($data['oid'])?null:$data['oid'];
        $uid = empty($data['uid'])?null:$data['uid'];
        $mid = empty($data['mid'])?null:$data['mid'];
        $class = !isset($data['class'])?null:$data['class'];
        $status = empty($data['status'])?null:$data['status'];

        //  分页
        $pnum = empty($data['pnum'])?'20':$data['pnum'];
        $page = empty($data['page']) ? '1' : $data['page'];
        //  调用的方法和要统计的字段
        $fucont = null;
        if(!empty($data['fu'])){
            $fucont['title'] = $data['fu'];
            $fucont['value'] = $data[$data['fu']];
        }
        $tclass = empty($data['f'])?'count':$data['f'];
        $value = empty($data['v'])?null:$data['v'];

        //  构造查询语句
        $query = new Query();
        $query = $query->name('order');
        $ora = $orb = null;
        if(!empty($fucont)){
            $ora = 'a.';
            $orb = 'b.';
            $query = $query->alias('a')->join("order_cont b",'b.oid = a.oid')->where("{$orb}{$fucont['title']}","{$fucont['value']}");
        }
        if(!empty($uid)){
            $query = $query->where("{$ora}uid",$uid);
            $map['uid'] = $uid;
        }
        if(!empty($oid)){
            $query = $query->where("{$ora}oid",$oid);
            $map['oid'] = $oid;
        }
        if(!empty($mid)){
            $query = $query->where("{$ora}mid",$mid);
            $map['mid'] = $mid;
        }
        //  根据class查询
        if(!empty($class) || isset($class)){
            $query = $query->where("{$ora}class",$class);
            $map['class'] = $class;
        }
        if(!empty($status)){
            $query = $query->where("{$ora}playstatus",'in',$status);
            $map['playstatus'] = array('in',$status);
        }
        //  计算 和
        $listmun = null;
        if(!empty($aid)){
            $query = $query->where("{$orb}aid","{$aid}");
        }

        switch ($tclass){
            case 'sum':
                $res = $query->sum($value);
                return $res;
                break;
            case 'count':
                $res = $query->count();
                return $res;
                break;
            case 'select':
                $query = $query->order("{$ora}addtime desc")->limit($pnum)->page($page);
                //  执行sql语句
                $_listdata = Db::select($query);
                //  获取所有数量
                $listmun = $this->where($map)->count();
                $pages = ceil($listmun/$pnum);
                //  格式化查询到的数据
                $listdata = null;
                if(!empty($_listdata)){
                    foreach ($_listdata as $k => $v){
                        $listdata[$k] = $this->unserializeData($v);
                    }
                }
                if(empty($listdata)){
                    return false;
                }else{
                    $res = array(
                        'list' => $listdata,
                        'pages' => $pages,
                        'page' => $page,
                        'pagenum' => $listmun,
                    );
                }
                return $res;
                break;
            case 'find':
                $cont = $query->find();
                if(empty($cont)){
                    return false;
                }
                $cont = $this->unserializeData($cont);
                return $cont;
                break;
        }

    }
    /**
     * @param $data 解压conf字段 ，格式化addtime时间,处理金额
     * @return mixed
     */
    protected function unserializeData($data){
        $data['conf'] = unserialize($data['conf']);
        $data['addtime'] = date("Y-m-d H:i:s",$data['addtime']);
        $data['allmoney'] = number_format($data['allmoney'] / 100,'2');
        $data['pricemoney'] = number_format($data['pricemoney'] / 100,'2');
        if(!empty($data['endtime'])){
            $data['endtime'] = date("Y-m-d H:i:s",$data['endtime']);
        }
        return $data;
    }

}